package com.polaris.live.manager

import android.content.Context
import android.text.TextUtils
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import com.lxj.xpopup.XPopup
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.AppModule
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.dialog.NormalNoticeDialog
import com.polaris.live.im.sfs.bean.pusher.PopupWindowMessage
import com.polaris.live.ui.login.LoginActivity
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * InstallReferrerUtils
 *
 * @author Created by 半仙 on 2024/2/26/026 11:09
 */
object GoogleInstallReferrerManager {

    private var referrerClient: InstallReferrerClient? = null
    private var reconnectJob: Job? = null

    private const val MAX_TIME = 10000L

    fun init(context: Context) {
        if (!AppModule.checkGoogleServices()) return

        if (referrerClient == null) {
            referrerClient = InstallReferrerClient.newBuilder(context).build()
        }
        connectReferrerClient()
    }

    private fun connectReferrerClient() {
        referrerClient?.run {
            if (!isReady) {
                // 发起连接
                startConnection(object : InstallReferrerStateListener {
                    override fun onInstallReferrerSetupFinished(responseCode: Int) {
                        if (responseCode == InstallReferrerClient.InstallReferrerResponse.OK) {
                            // 连接成功，可以获取安装引荐来源参数
                            try {
                                handlerInstallReferrerParams()
                            } catch (_: Throwable) {
                            }
                            // 处理完后释放资源
                            release()
                        } else {
                            // 连接失败，根据需求可以进行重连
                        }
                    }

                    override fun onInstallReferrerServiceDisconnected() {
                        // 与Google Play连接断开，10秒后进行重连
                        reconnect()
                    }
                })
            }
        }
    }

    private fun handlerInstallReferrerParams() {
        referrerClient?.run {
            if (isReady) {
                installReferrer.let {
                    // 安装引荐信息
                    val installReferrer = it.installReferrer
                    if (installReferrer.contains(CommonConst.Install.utmContent) && TextUtils.isEmpty(CommonCache.getInstall())) {
                        CommonCache.setInstall(installReferrer)
                        CommonCache.setInstallTime()
                    }

                    if (ServerConfig.isTestServer()) {
                        showTestDialog(it)
                    }
                }
            }
        }
    }

    private fun showTestDialog(details: ReferrerDetails) {
        // 安装引荐信息
        val installReferrer = details.installReferrer
        if (!installReferrer.contains(CommonConst.Install.utmContent)) {
            return
        }

        CoroutineScopeManager.mainScope.launch {
            delay(3000)
            ViewUtils.getAliveTopActivity()?.let { activity ->
                if (activity !is LoginActivity) {
                    return@launch
                }

                // 安装版本号
                val installVersion = details.installVersion
                // 开始安装的时间
                val installBeginTimestampSeconds = details.installBeginTimestampSeconds
                // 开始安装的服务器时间
                val installBeginTimestampServerSeconds = details.installBeginTimestampServerSeconds
                // 点击推荐信息的时间
                val referrerClickTimestampSeconds = details.referrerClickTimestampSeconds
                // 点击推荐信息的服务器时间
                val referrerClickTimestampServerSeconds = details.referrerClickTimestampServerSeconds
                // 过去7天是否参与过免安装体验
                val googlePlayInstantParam = details.googlePlayInstantParam

                val text = "安装引荐信息 = $installReferrer\n" +
                        "安装版本号 = $installVersion\n" +
                        "开始安装的时间 = $installBeginTimestampSeconds\n" +
                        "开始安装的服务器时间 = $installBeginTimestampServerSeconds\n" +
                        "点击推荐信息的时间 = $referrerClickTimestampSeconds\n" +
                        "点击推荐信息的服务器时间 = $referrerClickTimestampServerSeconds\n" +
                        "过去7天是否参与过免安装体验 = $googlePlayInstantParam"

                XPopup.Builder(activity)
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        NormalNoticeDialog(
                            activity, PopupWindowMessage(
                                text,
                                "{}",
                                title = "InstallReferrer",
                            )
                        )
                    )
                    .show()
            }
        }
    }

    private fun reconnect() {
        reconnectJob?.cancel()
        reconnectJob = CoroutineScopeManager.ioScope.launch {
            try {
                delay(MAX_TIME) // 10秒后进行重连
                connectReferrerClient()
            } finally {
                if (coroutineContext[Job] == reconnectJob) {
                    reconnectJob = null
                }
            }
        }
    }

    private fun release() {
        referrerClient?.endConnection()
        referrerClient = null

        reconnectJob?.cancel()
        reconnectJob = null
    }
}